package com.zhouyu.mysql;

import com.zhouyu.mysql.core.DTuple;
import com.zhouyu.mysql.core.DTupleUtil;
import net.sf.jsqlparser.statement.select.PlainSelect;

/**
 * 大都督周瑜（我的微信: dadudu6789）
 */
public class SqlOptimizer {

    public QEP_TAB optimize(PlainSelect plainSelect) {
        return new QEP_TAB(plainSelect);
    }

    // 里面其实有一个QEP_TAB属性，表示查询执行计划表，也就是执行计划
    static class QEP_TAB {

        private final SqlExecutor sqlExecutor = new SqlExecutor();

        private PlainSelect plainSelectStatement;

        public QEP_TAB(PlainSelect plainSelectStatement) {
            this.plainSelectStatement = plainSelectStatement;
        }

        public String exec() {

            DTuple dTuple = DTupleUtil.convert(plainSelectStatement);

            if (!dTuple.getFields().isEmpty()) {
                // 走索引
                return sqlExecutor.select(plainSelectStatement, false);
            } else {
                // 走全表扫描
                return sqlExecutor.select(plainSelectStatement, true);
            }


        }
    }


}
